
const express = require('express');
const fs=require('fs');
router = express.Router();

router.get('/sendip',(req,res)=>{
    let token='867785789';

    if(req.query.token!==token)
    {
        res.json({
            status:false,
            msg:'攻击我的都是彩笔~'
        });
        return;
    }

    let data={ip:get_client_ip(req).replace(/[^0-9.]/ig,'')};
    fs.writeFileSync(__dirname+'/ip.json',JSON.stringify(data));
   res.json({
       status:true,
       data:data,
       msg:"提交成功"
   })
});

router.get('/getip',(req,res)=>{
    let ip=fs.readFileSync(__dirname+'/ip.json','UTF-8').replace(/[^0-9.]/ig,'');
    res.json({
        status:true,
        ip:ip
    });
});

router.get('/nas',(req,res)=>{
    let ip=fs.readFileSync(__dirname+'/ip.json','UTF-8').replace(/[^0-9.]/ig,'');
    res.redirect('http://'+ip+':81')
});


function getClientIp(req) {
    var ipAddress;
    var forwardedIpsStr = req.header('x-forwarded-for');
    if (forwardedIpsStr) {
        var forwardedIps = forwardedIpsStr.split(',');
        ipAddress = forwardedIps[0];
    }
    if (!ipAddress) {
        ipAddress = req.connection.remoteAddress;
    }
    return ipAddress;
}

let get_client_ip = function(req) {
    return  req.headers['x-real-ip'] ? req.headers['x-real-ip'] : req.ip.replace(/::ffff:/, '');
};


router.get('/testip',(req,res)=>{
    res.send('当前设备IP地址为'+get_client_ip(req))
});


module.exports=router;
